<?php
/**
 * Created by lzl
 * Date: 2021 2021/11/1
 * Time: 16:13
 */
namespace App\Forms;

use App\Models\UserAddress;

class AddressForms extends BaseForm
{

    /**
     * 收货地址列表
     * @param $validated
     * @return mixed
     */
    public function addressList($validated)
    {
        $list = UserAddress::where('uid', $validated['uid'])
            ->page($validated['page'], $validated['limit'])
            ->orderBy('id', 'desc')
            ->get();
        return $list;
    }


    /**
     * 修改收货地址
     * @param $validated
     * @return UserAddress|\Illuminate\Database\Eloquent\Model
     */
    public function editAddress($validated)
    {
        if($validated['is_default']){
            UserAddress::where(['uid' => $validated['uid']])->update([
                'is_default' => UserAddress::UN_DEFAULT
            ]);
        }

        return UserAddress::updateOrCreate(['uid' => $validated['uid'], 'id' => $validated['id'] ?? 0], $validated);

    }



    /**
     * 删除
     * @param $validated
     * @return mixed
     */
    public function deleteAddress($validated)
    {
        return UserAddress::where($validated)->delete();
    }


    /**
     * 详情
     * @param $id
     * @return UserAddress|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function addressDetail($id)
    {
        return UserAddress::whereKey($id)->first();
    }


    /**
     * 默认地址
     * @param $uid
     * @return UserAddress|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function addressDefault($uid)
    {
        $address =  UserAddress::where('uid', $uid)->where('is_default', UserAddress::IS_DEFAULT)->first();

        if(blank($address)){
            $address =  UserAddress::where('uid', $uid)->first();
        }

        return $address;
    }
}